package com.gitee.starblues.example.jpa.service.quartz;

import com.gitee.starblues.example.jpa.dao.PluginJpaUserDao;
import com.gitee.starblues.example.jpa.entity.PluginJpaUser;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 数据库插入者启动的job
 * @author starBlues
 * @version 2.4.3
 */
public class DatabaseInsertJob implements Job {

    private static final Logger LOG = LoggerFactory.getLogger(DatabaseInsertJob.class);

    public static final String APPLICATION_CONTEXT = "applicationContext";

    private ApplicationContext applicationContext;
    private PluginJpaUserDao pluginJpaUserDao;

    private final AtomicInteger count = new AtomicInteger(0);

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap mergedJobDataMap = jobExecutionContext.getMergedJobDataMap();
        applicationContext = (ApplicationContext) mergedJobDataMap.get(APPLICATION_CONTEXT);
        pluginJpaUserDao = applicationContext.getBean(PluginJpaUserDao.class);
        insertUserData();
    }

    private void insertUserData() {
        LOG.info("开始插入jpa用户数据");
        PluginJpaUser user = new PluginJpaUser();
        int i = count.incrementAndGet();
        user.setUsername("jpa-" + i);
        user.setPassword("" + i);
        user.setDeleted(0);
        user.setName("name-" + i);
        user.setStatus(1);
        user.setLocked(2);
        pluginJpaUserDao.save(user);
    }


}
